<?php

function cable_comment_load($connector)
{
	/* DEPENDENCIES */
	/* check for comment template existence */
		
	$comment_table = "cable_".$connector->config['TablePrefix']."_comments";
	$captcha_table = "cable_".$connector->config['TablePrefix']."_comment_captchas";

	/* CREATION / PREP */
	$query = "CREATE TABLE IF NOT EXISTS $comment_table (id INT(6) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), user VARCHAR(64) NOT NULL, userip VARCHAR(16), parent INT(6), timestamp INT(10) NOT NULL, date INT(10) NOT NULL, text TEXT NOT NULL)";
	if (($result = mysql_query($query,$connector->db_link)) === false)
		return 'Error creating comment table.'.mysql_error();
		
	$query = "CREATE TABLE IF NOT EXISTS $captcha_table (id INT(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), question VARCHAR(256) NOT NULL, answer VARCHAR(16) NOT NULL)";
	if (($result = mysql_query($query,$connector->db_link)) === false)
		return 'Error creating captcha table.';
		
	$query = "SELECT COUNT(*) FROM $captcha_table";
	if (($result = mysql_query($query,$connector->db_link)) === false)
		return 'Error reading captcha table.';
	else
		list($itemcount) = mysql_fetch_row($result);
	
	if ($itemcount > 0)
		return true;
	
	$file_path = $cable_admin_plugin[connector]->config[SitePath]."plugins/cable_comment/captchas.txt";
	if (file_exists($file_path) && is_readable($file_path))
	{
		if (($file = file($file_path,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)) === false)
			return 'Error reading captchas.txt';
	
		foreach($file as $pair)
		{
			list($question,$answer) = explode('" "',$pair);
			$question = str_replace('"','',$question);
			$answer = str_replace('"','',$answer);
			
			$query = "INSERT INTO $captcha_table (question,answer) VALUES('$question','$answer')";
			mysql_query($query,$connector->db_link);
		}
	}
	else
		return 'Error opening captchas.txt';
	
	return true;
}

function cable_comment_unload($connector)
{
	/* drop tables if necessary */

	$comment_table = "cable_".$connector->config['TablePrefix']."_comments";
	$captcha_table = "cable_".$connector->config['TablePrefix']."_comment_captchas";
	
	if ($connector->config['PurgeCommentsOnUnload'] > 0)
	{
		$query = "DROP TABLE IF EXISTS $comment_table";
		if (($result = mysql_query($query,$connector->db_link)) === false)
			return 'Error dropping comment table';
	}
	
	if ($connector->config['PurgeCaptchasOnUnload'] > 0)
	{
		$query = "DROP TABLE IF EXISTS $captcha_table";
		if (($result = mysql_query($query,$connector->db_link)) === false)
			return 'Error dropping comment table';
	}

	return true;
}

function cable_comment_open($connector)
{
	/* this plugin has no caching behaviour */
	if ($connector->data[cached])
		return true;

	global $cable_comment_plugin;
	
	/* initialize our plugin global */
	$cable_comment_plugin = array('fail'=>true);
	
	/* copy connector data to our local global */
	$cable_comment_plugin[connector] = $connector;
	
	/* table names shorthand */
	$cable_comment_plugin[comment_table] = "cable_".$connector->config['TablePrefix']."_comments";
	$cable_comment_plugin[captcha_table] = "cable_".$connector->config['TablePrefix']."_comment_captchas";
	$cable_comment_plugin[user_table] = "cable_".$connector->config['TablePrefix']."_users";
	$cable_comment_plugin[entry_table] = "cable_".$connector->config['TablePrefix']."_entries";
	
	/* load template from db */
	$cable_comment_plugin[template] = new CABLEtemplate($connector->config,$connector->db,'cable_comment','comment');
	if ($cable_comment_plugin[template]->error)
		return 'Error retrieving cable_comment.comment template';

	/* load comment template */
	$cable_comment_plugin[comment_template] = $cable_comment_plugin[template]->GetChild('CABLE-Comment');
	if ($cable_comment_plugin[comment_template] === false)
		return 'Error retrieving comment template';
		
	/* retrieve date formats from template */
	$cable_comment_plugin[date_formats] = $cable_comment_plugin[template]->GetValue('CABLE-DateFormat',true);
	if (count($cable_comment_plugin[date_formats]) == 0)
		$cable_comment_plugin[date_formats] = array();
		
	/* initialize the template to recieve action changes to false */
	$cable_comment_plugin[action_template] = false;
	
	/* add the necessary css reference to the head of the template */
	$connector->template->AppendInsert('Head','<link type="text/css" href="{I CABLE-Base.url /}css/cable_comment/comment.css" rel="stylesheet" />');
	
	/* everything initialized ok */
	$cable_comment_plugin[fail] = false;
	
	return true;
}

function cable_comment_close($connector)
{
	/* delete the plugin global if we're not operating on cached material */
	if ($connector->data[cached])
		return true;
	
	global $cable_comment_plugin;
	
	/* sanity check */
	if ($cable_comment_plugin[fail])
		return true;
	
	/* delete the plugin global */
	unset($cable_comment_plugin);
	
	return true;
}

function cable_comment(&$connector)
{
	/* this plugin has no caching behaviour */
	if ($connector->data[cached])
		return true;

	global $cable_comment_plugin;
	
	/* sanity check */
	if ($cable_comment_plugin[fail])
		return true;
	
	/* perform necessary top-level actions */
	switch (urldecode($_REQUEST['comment_action']))
	{
		case 'new':
		case 'reply':
			if (($ret = CABLE_commentBuildCompose()) !== true)
				return $ret;
			break;
		case 'preview':
			if (($ret = CABLE_commentBuildPreview()) !== true)
				return $ret;
			break;
		case 'save':
			if (($ret = CABLE_commentSaveComment()) !== true)
				return $ret;
			break;
		case 'delete':
			if (($ret = CABLE_commentDeleteComment()) !== true)
				return $ret;
			break;
	}
	
	/* load top-level comments from database */
	$query = "SELECT * FROM ".$cable_comment_plugin[comment_table]." WHERE (timestamp = '".$connector->data['timestamp']."') AND ((parent IS NULL) OR (parent = '')) ORDER BY date ASC";
	if(($result = mysql_query($query,$connector->db_link)) !== false)
	{
		while($data = mysql_fetch_array($result,MYSQL_ASSOC))
		{
			if (($comment = BuildComment($data, 0)) !== false)
				$cable_comment_plugin[template]->AppendInsert('CABLE-Comments',$comment);
		}
	}
	else
		return 'Error accessing comment table';
		
	/* replace top level inserts */
	if ($cable_comment_plugin[action_template] !== false)
	{
		$cable_comment_plugin[template]->ReplaceInsert('CABLE-Compose',$cable_comment_plugin[action_template]->template);
		$cable_comment_plugin[action_template] = false;
	}
	
	/* set booleans */	
	/* commenting timeout */
	$value = ((((time() - $connector->config[CommentTimeout]) < $connector->data['timestamp']) && ($connector->data[commentable] == 1)) || ($connector->config[CommentTimeout] == -1));
	$cable_comment_plugin[template]->SetBool('CABLE-Comments.active',$value);
	
	/* strip out extraneous template blocks from final product */
	$cable_comment_plugin[template]->ReplaceChild('CABLE-Comment','');
	$cable_comment_plugin[template]->ReplaceChild('CABLE-Compose','');
	$cable_comment_plugin[template]->ReplaceChild('CABLE-Preview','');

	/* write complete comment source to parent template */
	$connector->template->ReplaceInsert('CABLE-Comments',$cable_comment_plugin[template]->template);
	
	/* free up memory */
	unset ($cable_comment_plugin);
	
	return true;
}

function BuildComment($data,$depth)
{
	global $cable_comment_plugin;
	
	/* roll back the template to the unchanged state */
	$comment_template = clone $cable_comment_plugin[comment_template];
	unset($comment_template->messages);
	$comment_template->Reset();

	/* retrieve children from database */
	$query = "SELECT * FROM ".$cable_comment_plugin[comment_table]." WHERE (parent = '".$data['id']."') AND (parent > 0) ORDER BY date ASC";
	if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
		return false;
		
	/* if children exist, retrieve the info and append it to the reply source html */
	if (mysql_num_rows($result) > 0)
	{
		$reply_text = '';
		while($reply_data = mysql_fetch_array($result,MYSQL_ASSOC))
		{
			if (($reply = BuildComment($reply_data, $depth+1)) !== false)
				$comment_template->AppendInsert('CABLE-Replies',$reply);
		}
	}
	
	/* perform necessary comment-level actions */
	if ($data['id'] == $_REQUEST['comment_id'])
	{		
		switch (urldecode($_REQUEST['comment_action']))
		{
			case 'reply':
			case 'preview':
			case 'save':
				$comment_template->ReplaceInsert('CABLE-Reply',$cable_comment_plugin[action_template]->template);
				$cable_comment_plugin[action_template] = false;
				break;
		}
	}
	
	/* do date replacements */
	foreach($cable_comment_plugin[date_formats] as $i => $f)
		$comment_template->ReplaceInsert('CABLE-Date.'.$i,date($f,$data['date']));
	
	/* set entry attributes */
	$comment_template->ReplaceInsert('CABLE-ID',$data['id']);
	$comment_template->ReplaceInsert('CABLE-Depth',$depth);
	$comment_template->ReplaceInsert('CABLE-Parent.id',$data['parent']);
	$comment_template->ReplaceInsert('CABLE-Author.username',urldecode(stripslashes($data['user'])));
	$comment_template->ReplaceInsert('CABLE-Author.ip',urldecode($data['userip']));
	$comment_template->ReplaceInsert('CABLE-Html',nl2br(rawurldecode($data['text'])));
	$comment_template->ReplaceInsert('CABLE-Replies',$reply_text);
	
	/* return the finished comment */
	return $comment_template->template;
}

function CABLE_commentBuildCompose()
{
	global $cable_comment_plugin;
	
	$cable_comment_plugin[action_template] = $cable_comment_plugin[template]->GetChild('CABLE-Compose');
	if ($cable_comment_plugin[action_template] === false)
		return 'Error retrieving composition template';
				
	$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Text',rawurldecode($_REQUEST['comment_text']));
	$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Html',nl2br(urldecode($_REQUEST['comment_text'])));

	return true;
}

function CABLE_commentBuildPreview()
{
	global $cable_comment_plugin;

	$cable_comment_plugin[action_template] = $cable_comment_plugin[template]->GetChild('CABLE-Preview');
	if ($cable_comment_plugin[preview] === false)
		return 'Error retrieving preview template';
	
	/* do captcha if necessary */
	if ($cable_comment_plugin[connector]->config[UseCaptcha])
	{
		$query = "SELECT id,question FROM ".$cable_comment_plugin[captcha_table]." ORDER BY RAND() LIMIT 1";
		if (($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error accessing captcha table';
		$captcha = mysql_fetch_assoc($result);

		$cable_comment_plugin[action_template]->SetBool('CABLE-Captcha',true);
		$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Captcha.question',$captcha[question]);
		$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Captcha.id',$captcha[id]);
	}
	else
		$cable_comment_plugin[action_template]->SetBool('CABLE-Captcha',false);
	
	/* do date replacements */
	foreach($cable_comment_plugin[date_formats] as $i => $f)
		$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Date.'.$i,date($f));

	$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Text',rawurlencode(stripslashes($_REQUEST['comment_text'])));
	$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Html',nl2br(stripslashes(urldecode($_REQUEST['comment_text']))));
	
	return true;
}

function CABLE_commentSaveComment()
{
	global $cable_comment_plugin;
	
	/* chcek for appropriate catpcha response */
	if ($cable_comment_plugin[connector]->config[UseCaptcha])
	{	
		/* do captcha if necessary */
		$query = "SELECT answer FROM ".$cable_comment_plugin[captcha_table]." where id='".str_replace('"','',str_replace('\'','',$_REQUEST['comment_captcha_id']))."' LIMIT 1";
		if (($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error accessing captcha table';
		$row = mysql_fetch_row($result);

		if ($row[0] !== strtolower(urldecode($_REQUEST['comment_captcha_answer'])))
		{
			if (($ret = CABLE_commentBuildCompose()) !== true)
			return ret;
			
			$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
			$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Incorrect captcha answer.');
		
			return true;
		}
	}
	
	/* check for timeout / entry comment locking */
	if ((((time() - $cable_comment_plugin[connector]->config[CommentTimeout]) > $cable_comment_plugin[connector]->data['timestamp']) || ($connector->data[commentable] != 1)) && ($cable_comment_plugin[connector]->config[CommentTimeout] != -1))
	{
		if (($ret = CABLE_commentBuildCompose()) !== true)
			return $ret;
			
		$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Commenting is disabled for this entry.');
		return true;
	}
	
	/* check and make sure the user is logged in */
	if ((!$cable_comment_plugin[connector]->user->logged_in) && ($cable_comment_plugin[connector]->config[AllowAnonymous] != 1))
	{
		if (($ret = CABLE_commentBuildCompose()) !== true)
			return $ret;
			
		$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Anonymous commenting is not allowed. Please sign in to comment.');
		return true;
	}
	
	/* check for number of times this IP has posted */
	if ($cable_comment_plugin[connector]->config[CommentLimit] > 0)
	{
		$query = "SELECT COUNT(*) FROM ".$cable_comment_plugin[comment_table]." WHERE (userip = '".str_replace('"','',str_replace('\'','',$_ENV[REMOTE_ADDR]))."') AND (date > '".(time() -86400)."')";
		if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error accessing comment table';
		$row = mysql_fetch_row($result);
		if ($row[0] > $cable_comment_plugin[connector]->config[CommentLimit])
		{
			if (($ret = CABLE_commentBuildCompose()) !== true)
				return $ret;
				
			$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
			$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','You have commented too many times in 24 hours, please wait until resubmitting.');
			return true;
		}
	}
	
	/* check for existing username conflicts */
	if ($cable_comment_plugin[connector]->user->values[username] != 'Anonymous')
	{
		$query = "SELECT COUNT(*) FROM ".$cable_comment_plugin[user_table]." WHERE username = '".$cable_comment_plugin[connector]->user->values[username]."' LIMIT 1";
		if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error accessing user table';
		$row = mysql_fetch_row($result);
		if (($row[0] > 0) && (!$cable_comment_plugin[connector]->user->logged_in))
		{
			if (($ret = CABLE_commentBuildCompose()) !== true)
				return $ret;
				
			$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
			$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','You have selected a username that already exists.');
			return true;
		}
	}
	
	/* check if it's a banned ip/username */
	/* check for existing username conflicts */
	if ($cable_comment_plugin[connector]->user->values[username] != 'Anonymous')
	{
		$query = "SELECT COUNT(*) FROM ".$cable_comment_plugin[user_table]." WHERE (fullname='".$_ENV[REMOTE_ADDR]."' OR username='".$cable_comment_plugin[connector]->user->values[username]."') AND (adminlevel < 0) LIMIT 1";
		if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error accessing user table';
		$row = mysql_fetch_row($result);
		if ($row[0] > 0)
		{
			echo $query;
			if (($ret = CABLE_commentBuildCompose()) !== true)
				return $ret;
				
			$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
			$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','This username or IP is banned from posting.');
			return true;
		}
	}
	
	/* attempt to insert comment */
	$query = "INSERT INTO ".$cable_comment_plugin[comment_table]." (date,timestamp,user,userip,parent,text) VALUES ('".
	time()."','".
	$cable_comment_plugin[connector]->data[timestamp]."','".
	$cable_comment_plugin[connector]->user->values[username]."','".
	str_replace('"','',str_replace('\'','',$_ENV[REMOTE_ADDR]))."','".
	str_replace('"','',str_replace('\'','',$_REQUEST['comment_id']))."','".
	str_replace('"','',str_replace('\'','',$_REQUEST['comment_text']))."')";
	
	if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
	{
		if (($ret = CABLE_commentBuildCompose()) !== true)
			return $ret;
			
		$cable_comment_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_comment_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Your comment could not be submitted.');
		return true;
	}
	
	/* update entry commentcount */
	$query = "SELECT data FROM ".$cable_comment_plugin[entry_table]." WHERE timestamp='".$cable_comment_plugin[connector]->data[timestamp]."' LIMIT 1";
	if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
		return 'Error retrieving entry comment count';
	if (mysql_num_rows($result) > 0)
	{
		$row = mysql_fetch_row($result);
		$data = unserialize($row[0]);
		$data[num_comments]++;
	
		$query = "UPDATE ".$cable_comment_plugin[entry_table]." SET data='".serialize($data)."' WHERE timestamp='".$cable_comment_plugin[connector]->data[timestamp]."' LIMIT 1";
		if(($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error updating entry comment count';
	}

	return true;
}

function CABLE_commentDeleteComment()
{
	global $cable_comment_plugin;

	if ($cable_comment_plugin[connector]->user->values[adminlevel] < 1)
		return true;
		
	$comment_id = (int)(urldecode($_REQUEST['comment_id']));
	/* get the author of the comment */
	$query = "SELECT user FROM ".$cable_comment_plugin[comment_table]." WHERE (id=$comment_id) LIMIT 1";
	if (($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
		return 'Error retrieving comment information';
	list($author) = mysql_fetch_row($result);
	
	/* check and make sure that the administrator requesting the delete has a high enough adminlevel */
	$query = "SELECT adminlevel FROM ".$cable_comment_plugin[user_table]." WHERE (username='$author') LIMIT 1";
	if (($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
		return 'Error retrieving comment user information';
	list ($adminlevel) = mysql_fetch_row($result);
	
	/* if the logged in admin is root or is more priviledged than the user who owns the comment, delete it */
	if (($adminlevel < $cable_comment_plugin[connector]->user->values[adminlevel]) || ($cable_comment_plugin[connector]->user->values[adminlevel] == 2))
	{
		$query = "DELETE FROM ".$cable_comment_plugin[comment_table]." WHERE (id=$comment_id) LIMIT 1";
		if (($result = mysql_query($query,$cable_comment_plugin[connector]->db_link)) === false)
			return 'Error deleting comment.';
	}	
	
	return true;
}

?>